package com.ybkj.daijia.serverUtils;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import javax.imageio.ImageIO;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;
import org.springframework.web.multipart.MultipartFile;

/**
 * @author zhyu
 * @date 2019/12/16 16:31
 */
public class IOUtils {

    public static void main(String[] args) {
        System.out.println(readFileToBase64("G://images/driver1Idcardback.png"));
    }

    public static final Logger log = LoggerFactory.getLogger(IOUtils.class);

    public static void convertPngToJpg(File file,String newFilePath){
        try {
            BufferedImage bufferedImage = ImageIO.read(file);
            BufferedImage newBufferedImage = new BufferedImage(bufferedImage.getWidth(),bufferedImage.getHeight(),BufferedImage.TYPE_INT_RGB);
            newBufferedImage.createGraphics().drawImage(bufferedImage, 0, 0, null);
            ImageIO.write(newBufferedImage,"jpg",new File(newFilePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String readFileToBase64(String path) {
        byte[] bytes = readFileToByteArray(path);
        if (bytes == null) {
            return null;
        }
        return Base64.getEncoder().encodeToString(bytes);
    }

    /**
     * 图片转化成base64字符串
     *
     * @param in
     * @return
     */
    public static String readBase64FromInputStream(InputStream in) {
        //将图片文件转化为字节数组字符串，并对其进行Base64编码处理
        byte[] data = null;
        //读取图片字节数组
        try {
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //对字节数组Base64编码
        return Base64Utils.encodeToString(data).replaceAll("\r|\n", "");
    }


    /**
     * base64字符串转化成图片
     *
     * @param imgStr
     * @return
     */
    public static boolean readBase64ToFile(String imgStr, String path, String fileName) {
        //图像数据为空
        if (null == imgStr || null == path || null == fileName) {
            return false;
        }
        try {
            //Base64解码
            byte[] b = Base64Utils.decodeFromString(imgStr);
            for (int i = 0; i < b.length; ++i) {
                //调整异常数据
                if (b[i] < 0) {
                    b[i] += 256;
                }
            }
            //生成jpeg图片 //新生成的图片
            String name;
            if (path.endsWith("/") || path.endsWith("\\")) {
                name = path + fileName;
            } else {
                name = path + File.separator + fileName;
            }
            OutputStream out = new FileOutputStream(name);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 根据文件路径获取文件的byte数组
     *
     * @param path
     * @return
     */
    public static byte[] readFileToByteArray(String path) {
        FileInputStream fileInputStream;
        byte[] bytes = null;
        try {
            fileInputStream = new FileInputStream(path);
            int available = fileInputStream.available();
            bytes = new byte[available];
            fileInputStream.read(bytes);
            fileInputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return bytes;
    }

    /***
     * 根据路径,MutilpartFile储存文件, 文件名取  日期_1000以内的随机数.指定后缀
     * @param path
     * @param qualificationPhoto
     * @param formateStr
     * @return
     */
    public static String saveFileInLocalByMultipartFileFormateNameAndPath(String path, MultipartFile qualificationPhoto, String formateStr) {
        try {
            File dir = new File(path);
            FileUtils.forceMkdir(dir);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = String
                .format(formateStr, df.format(new Date()) + "_" + new Random().nextInt(1000));
            //读取照片字节，存入文件夹中
            byte[] data = qualificationPhoto.getBytes();
            File newFile = new File(dir, fileName);
            FileOutputStream out = new FileOutputStream(newFile);
            org.apache.commons.io.IOUtils.write(data, out);
            org.apache.commons.io.IOUtils.closeQuietly(out);
            return fileName;
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("存入文件错误");
            }
        }
        return null;
    }

    /***
     * 根据路径,MutilpartFile储存文件, 文件名取  日期_1000以内的随机数.指定后缀
     * @param path
     * @param qualificationPhoto
     * @param formateStr
     * @param sizes
     * @return
     */
    public static String savePhotoFileInLocalByMultipartFileFormateNameAndPath(String path, MultipartFile qualificationPhoto, String formateStr, int[] sizes) {
        try {
            File dir = new File(path);
            FileUtils.forceMkdir(dir);
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String fileName = String
                .format(formateStr, df.format(new Date()) + "_" + new Random().nextInt(1000));
            //读取照片字节，存入文件夹中
            byte[] data = qualificationPhoto.getBytes();
            File newFile = new File(dir, fileName);
            FileOutputStream out = new FileOutputStream(newFile);
            org.apache.commons.io.IOUtils.write(data, out);
            if (sizes != null) {
                Thumbnails.of(newFile).size(sizes[0], sizes[1]).toFile(newFile);
            }
            org.apache.commons.io.IOUtils.closeQuietly(out);
            return fileName;
        } catch (Exception e) {
            if (log.isErrorEnabled()) {
                log.error("存入图片错误");
            }
        }
        return null;
    }
}
